package net.ak.utils;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class EncriptUtils {

	private final static EncriptUtils encriptUtil = new EncriptUtils();
	private static String algorithm = "AES";
	private static byte[] keyValue = "whatisyourpasswd".getBytes();
	private static final BASE64Encoder base64Encoder = new BASE64Encoder();
	private static final BASE64Decoder base64Decoder = new BASE64Decoder();

	private EncriptUtils() {
	}

	public static EncriptUtils getInstance() {
		return encriptUtil;
	}

	/**
	 * Performs Encryption
	 * 
	 * @param plainText
	 * @return
	 * @throws Exception
	 */
	public String encrypt(String plainText) {
		try {
			Key key = generateKey();
			Cipher chiper = Cipher.getInstance(algorithm);
			chiper.init(Cipher.ENCRYPT_MODE, key);
			byte[] encVal = chiper.doFinal(plainText.getBytes());
			String encryptedValue = base64Encoder.encode(encVal);

			return encryptedValue;
		} catch (Exception e) {

		}

		return null;
	}

	/**
	 * Performs decryption
	 * 
	 * @param encryptedText
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String encryptedText) {
		try {
			Key key = generateKey();
			Cipher chiper = Cipher.getInstance(algorithm);
			chiper.init(Cipher.DECRYPT_MODE, key);
			byte[] decordedValue = base64Decoder.decodeBuffer(encryptedText);
			byte[] decValue = chiper.doFinal(decordedValue);
			String decryptedValue = new String(decValue);

			return decryptedValue;
		} catch (Exception e) {

		}

		return null;
	}

	/**
	 * generateKey() is used to generate a secret key for AES algorithm
	 * 
	 * @return
	 * @throws Exception
	 */
	private Key generateKey() {
		Key key = new SecretKeySpec(keyValue, algorithm);
		return key;
	}

	/**
	 * This method is used to generate md5 hash value.
	 * @param text
	 * @return
	 */
	public String md5Encrypt(String text) {
		if (text == null) return "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(text.getBytes());
			byte byteData[] = md.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static void main(String[] args) {
		System.out.println(getInstance().md5Encrypt("123456"));
	}
}
